/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package morseSide;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Allan Helbling
 */
public class SocketOut {

    private Socket socket = null;
    InputStream is = null;

    public SocketOut(InetAddress ip, int port) {
        try {
            //socket = new Socket(InetAddress.getLocalHost(), 4000); // Toujours 4000 par défaut
            setSocket(new Socket(ip, port));
        } catch (IOException ex) {
            Logger.getLogger(SocketOut.class.getName()).log(Level.SEVERE, null, ex);
            //System.out.println("Problème lors de la création du socketOut");

        }


    }

    public void sendMessage(String message) {
        try {
            String str = "", str2 = "";
            //socket.getOutputStream().write("id1 atrv.motion set_speed [2, -1]\n".getBytes());
            getSocket().getOutputStream().write((message + "\n").getBytes());
            //On récupère le message de retour : id SUCCESS
//            is = socket.getInputStream();
//            int c;
//            while ((c = is.read()) != -1) {
//                str2 = new Character((char) c).toString();
//                str = str + str2;
//                System.out.write(c);
//            }
        } catch (Exception e) {
            System.err.println("Exception " + e.toString());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    Logger.getLogger(SocketOut.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
    }

    public void close() {
        if (getSocket() != null) {
            try {
                getSocket().close();
            } catch (IOException ex) {
                System.out.println("Problème lors de la fermeture du socketOut sur l'adresse " + getSocket().getInetAddress() + "sur le port" + getSocket().getPort());
            }
        }
    }

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}
}
